package com.sqx.modules.orders.controller;

import com.sqx.common.utils.Result;
import com.sqx.modules.app.annotation.Login;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.orders.entity.Orders;
import com.sqx.modules.orders.service.OrdersService;
import com.sqx.modules.taking.entity.OrderTaking;
import com.sqx.modules.taking.service.OrderTakingService;
import com.sqx.modules.task.dao.HelpOrderDao;
import com.sqx.modules.utils.SenInfoCheckUtil;
import com.sqx.modules.utils.excel.ExcelData;
import com.sqx.modules.utils.excel.ExportExcelUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/orders")
@Api(value = "订单信息", tags = {"订单信息"})
public class OrdersController {
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private UserService userService;
    @Autowired
    private HelpOrderDao helpOrderDao;
    @Autowired
    private CommonInfoService commonInfoService;
    @Autowired
    private OrderTakingService orderTakingService;

    /**
     * 查看所有订单
     *
     * @param page
     * @param limit
     * @param
     * @param status
     * @return
     */
    @RequestMapping("/queryOrders")
    public Result queryOrdersAll(Long page, Long limit, Long type, String userName,String ordersUserName, Long status, Long userId, String ordersNo, String startTime, String endTime, Long orderTakingUserId, String companyName) {
        return ordersService.queryOrdersAll(page, limit, type, userName,ordersUserName, status, userId, ordersNo, startTime, endTime, orderTakingUserId, companyName);
    }

    @GetMapping("/ordersListExcel")
    @ApiOperation("订单导出")
    public void ordersListExcel(Long type, String name, Long status, Long userId, String ordersNo, String startTime, String endTime, HttpServletResponse response) throws Exception {
        ExcelData data = ordersService.ordersListExcel(type, name, status, userId, ordersNo, startTime, endTime);
        ExportExcelUtils.exportExcel(response, "订单列表.xlsx", data);
    }

    /**
     * 删除订单
     */
    @RequestMapping("/deleteOrders")
    public Result deleteOrders(Long id) {
        return ordersService.deleteOrder(id);
    }

    @GetMapping("/selectMyTakeOrders")
    @ApiOperation("查询我的接单")
    public Result selectMyTakeOrders(Integer page, Integer limit, Long userId, Integer status, Long staffUserId, String name, String phone, String startTime, String staffUserName, String ordersNo) {
        return ordersService.selectMyTakeOrders(page, limit, userId, status, staffUserId, name, phone, startTime, staffUserName, ordersNo);
    }

    @ApiOperation("修改订单状态")
    @GetMapping("/cancelOrder")
    public Result cancelOrder(Long id, String status, String startServiceImg, String endServiceImg, BigDecimal money,
                              String startServiceLongitude, String startServiceLatitude,
                              String endServiceLongitude, String endServiceLatitude) {
        Orders orders = ordersService.getById(id);
        return ordersService.cancelOrder(id, status, orders.getCode(), startServiceImg, endServiceImg, money,
                startServiceLongitude, startServiceLatitude, endServiceLongitude, endServiceLatitude,2);
    }

    @GetMapping("/selectTeamOrdersList")
    @ApiOperation("获取团队订单")
    public Result selectTeamOrdersList(Long userId, Integer page, Integer limit, Integer type, Integer status) {
        return ordersService.selectTeamOrdersList(page, limit, userId, type, status);
    }


    @GetMapping("/selectTeamUserList")
    @ApiOperation("获取团队列表")
    public Result selectTeamUserList(Long userId, Integer page, Integer limit, Integer type) {
        UserEntity user = userService.selectUserById(userId);
        return ordersService.selectTeamUserList(page, limit, user.getInvitationCode(), type, userId);
    }

    @GetMapping("/selectTeamStatistics")
    @ApiOperation("团队统计")
    public Result selectTeamStatistics(Long userId, Integer type) {
        UserEntity user = userService.selectUserById(userId);
        Double teamMoney = ordersService.selectOrdersMoneyCountByUserId(user.getUserId(), type);
        Integer teamCount = ordersService.selectUserCountByInvitationCode(user.getInvitationCode(), type);
        Map<String, Object> result = new HashMap<>();
        result.put("teamMoney", teamMoney);
        result.put("teamCount", teamCount);
        return Result.success().put("data", result);
    }

    @ApiOperation("修改订单预约时间")
    @GetMapping("/updateStartTime")
    public Result updateStartTime(Long ordersId, String startTime, String remarks) {
        Orders orders = ordersService.getById(ordersId);
        orders.setStartTime(startTime);
        orders.setRemarks(remarks);
        ordersService.updateById(orders);
        return Result.success();
    }

    @PostMapping("/assignTask")
    @ApiOperation("指派员工")
    public Result assignTask(Long userId, Long ordersId) {
        Orders orders = ordersService.getById(ordersId);
        orders.setStaffUserId(userId);
        ordersService.updateById(orders);//消息推送
        UserEntity userEntity = userService.selectUserById(userId);
        String templateId = commonInfoService.findOne(621).getValue();
        if(StringUtils.isNotBlank(userEntity.getOpenId())){
            List<String> msgList=new ArrayList<>();
            msgList.add(orders.getOrdersNo());
            OrderTaking orderTaking = orderTakingService.getById(orders.getOrderTakingId());
            String serviceName = orderTaking.getGameId();
            if(serviceName.length()>15){
                serviceName=serviceName.substring(0,15)+"...";
            }
            msgList.add(serviceName);
            msgList.add(orders.getStartTime());
            msgList.add(orders.getName());
            SenInfoCheckUtil.sendMsg(userEntity.getOpenId(),templateId,null,msgList,6);
        }
        if(StringUtils.isNotBlank(userEntity.getPhone())){
            userService.sendMsg(userEntity.getPhone(),"assignTask",null);
        }
        return Result.success();
    }

    @GetMapping("/selectStaffUserOrdersByTime")
    @ApiOperation("员工订单统计")
    public Result selectStaffUserOrdersByTime(Integer page, Integer limit, Long companyId, String startTime, String endTime, String phone, String userName) {
        return ordersService.selectStaffUserOrdersByTime(page, limit, companyId, startTime, endTime, phone, userName);
    }

    @GetMapping("/selectOrdersStatistics")
    @ApiOperation("订单接单统计")
    public Result selectOrdersStatistics(String time, Integer flag) {
        /**
         * 管理后台 需要新增
         * 订单统计 和接单统计 不同状态，
         *
         *
         */
        //订单状态 0待支付1进行中2已完成3已退款4待服务
        Integer serviceJinXingCount = ordersService.selectOrdersCountByStatusAndTime(time, flag, 1);
        Integer serviceWanChengCount = ordersService.selectOrdersCountByStatusAndTime(time, flag, 2);
        Integer serviceTuiKuanCount = ordersService.selectOrdersCountByStatusAndTime(time, flag, 3);
        Integer serviceDaiFuWuCount = ordersService.selectOrdersCountByStatusAndTime(time, flag, 4);
        BigDecimal serviceMoney = ordersService.sumOrdersByCreateTime(time, flag, null);

        //1待审核 2待接单 3待送达 4已完成  5取消
        Integer helpOrderDaiShenHeCount = helpOrderDao.selectHelpOrderCountByStatusAndTime(time, flag, 1);
        Integer helpOrderDaiJieDanCount = helpOrderDao.selectHelpOrderCountByStatusAndTime(time, flag, 2);
        Integer helpOrderDaiSongDaCount = helpOrderDao.selectHelpOrderCountByStatusAndTime(time, flag, 3);
        Integer helpOrderYiWanChengCount = helpOrderDao.selectHelpOrderCountByStatusAndTime(time, flag, 4);
        Integer helpOrderYiQuXiaoCount = helpOrderDao.selectHelpOrderCountByStatusAndTime(time, flag, 5);
        Double helpOrderMoney = helpOrderDao.selectHelpOrderMoneyByStatusAndTime(time, flag, null);

        Map<String, Object> result = new HashMap<>();
        result.put("serviceJinXingCount", serviceJinXingCount);
        result.put("serviceWanChengCount", serviceWanChengCount);
        result.put("serviceTuiKuanCount", serviceTuiKuanCount);
        result.put("serviceDaiFuWuCount", serviceDaiFuWuCount);
        result.put("serviceMoney", serviceMoney);
        result.put("HelpOrderDaiShenHeCount", helpOrderDaiShenHeCount);
        result.put("HelpOrderDaiJieDanCount", helpOrderDaiJieDanCount);
        result.put("HelpOrderDaiSongDaCount", helpOrderDaiSongDaCount);
        result.put("HelpOrderYiWanChengCount", helpOrderYiWanChengCount);
        result.put("HelpOrderYiQuXiaoCount", helpOrderYiQuXiaoCount);
        result.put("HelpOrderMoney", helpOrderMoney);
        return Result.success().put("data", result);
    }

    @GetMapping("/selectOrdersToTal")
    @ApiOperation("订单累计")
    public Result selectOrdersToTal() {
        //新增累计订单，总金额，待服务，开始服务，结束服务
        //订单状态 0待支付1进行中2已完成3已退款4待服务
        Integer serviceCount = ordersService.selectOrdersCountByStatusAndTime(null, null, null);
        Integer serviceJinXingCount = ordersService.selectOrdersCountByStatusAndTime(null, null, 1);
        Integer serviceWanChengCount = ordersService.selectOrdersCountByStatusAndTime(null, null, 2);
        Integer serviceTuiKuanCount = ordersService.selectOrdersCountByStatusAndTime(null, null, 3);
        Integer serviceDaiFuWuCount = ordersService.selectOrdersCountByStatusAndTime(null, null, 4);
        BigDecimal serviceMoney = ordersService.sumOrdersByCreateTime(null, null, null);

        //1待审核 2待接单 3待送达 4已完成  5取消
        Integer helpOrderCount = helpOrderDao.selectHelpOrderCountByStatusAndTime(null, null, null);
        Integer helpOrderDaiShenHeCount = helpOrderDao.selectHelpOrderCountByStatusAndTime(null, null, 1);
        Integer helpOrderDaiJieDanCount = helpOrderDao.selectHelpOrderCountByStatusAndTime(null, null, 2);
        Integer helpOrderDaiSongDaCount = helpOrderDao.selectHelpOrderCountByStatusAndTime(null, null, 3);
        Integer helpOrderYiWanChengCount = helpOrderDao.selectHelpOrderCountByStatusAndTime(null, null, 4);
        Integer helpOrderYiQuXiaoCount = helpOrderDao.selectHelpOrderCountByStatusAndTime(null, null, 5);
        Double helpOrderMoney = helpOrderDao.selectHelpOrderMoneyByStatusAndTime(null, null, null);

        Map<String, Object> result = new HashMap<>();
        result.put("serviceCount", serviceCount);
        result.put("HelpOrderCount", helpOrderCount);
        result.put("serviceJinXingCount", serviceJinXingCount);
        result.put("serviceWanChengCount", serviceWanChengCount);
        result.put("serviceTuiKuanCount", serviceTuiKuanCount);
        result.put("serviceDaiFuWuCount", serviceDaiFuWuCount);
        result.put("serviceMoney", serviceMoney);
        result.put("HelpOrderDaiShenHeCount", helpOrderDaiShenHeCount);
        result.put("HelpOrderDaiJieDanCount", helpOrderDaiJieDanCount);
        result.put("HelpOrderDaiSongDaCount", helpOrderDaiSongDaCount);
        result.put("HelpOrderYiWanChengCount", helpOrderYiWanChengCount);
        result.put("HelpOrderYiQuXiaoCount", helpOrderYiQuXiaoCount);
        result.put("HelpOrderMoney", helpOrderMoney);
        return Result.success().put("data", result);
    }

    @GetMapping("/selectOrdersToTalByUserId")
    @ApiOperation("订单累计")
    public Result selectOrdersToTal(Integer flag,String time,Long userId) {
        //状态  1待服务 2服务中 3已完成 4已取消
        Integer helpTakeCount = helpOrderDao.selectHelpTakeCountByStatusAndTime(time, flag, null,userId);
        Integer helpTakeDaiFuWuCount = helpOrderDao.selectHelpTakeCountByStatusAndTime(time, flag, 1,userId);
        Integer helpTakeFuWuZhongCount = helpOrderDao.selectHelpTakeCountByStatusAndTime(time, flag, 2,userId);
        Integer helpTakeYiWanChengCount = helpOrderDao.selectHelpTakeCountByStatusAndTime(time, flag, 3,userId);
        Integer helpTakeYiQuXiaoCountCount = helpOrderDao.selectHelpTakeCountByStatusAndTime(time, flag, 4,userId);
        Double helpTakeMoney = helpOrderDao.selectHelpTakeMoneyByStatusAndTime(time, flag, userId);

        Map<String, Object> result = new HashMap<>();
        result.put("helpTakeCount", helpTakeCount);
        result.put("helpTakeDaiFuWuCount", helpTakeDaiFuWuCount);
        result.put("helpTakeFuWuZhongCount", helpTakeFuWuZhongCount);
        result.put("helpTakeYiWanChengCount", helpTakeYiWanChengCount);
        result.put("helpTakeYiQuXiaoCountCount", helpTakeYiQuXiaoCountCount);
        result.put("helpTakeMoney", helpTakeMoney);
        return Result.success().put("data", result);
    }


    @GetMapping("/selectOrdersPayStatistics")
    @ApiOperation("订单支付统计")
    public Result selectOrdersPayStatistics(String time, Integer flag) {
        //收益统计，新增微信支付统计，支付宝支付统计，钱包支付统计，

        //万能任务 1零钱 2微信  3支付宝
        Double helpOrderLingQianMoney = helpOrderDao.selectHelpOrderMoneyByStatusAndTime(time, flag, 1);
        Double helpOrderWxMoney = helpOrderDao.selectHelpOrderMoneyByStatusAndTime(time, flag, 2);
        Double helpOrderZFBMoney = helpOrderDao.selectHelpOrderMoneyByStatusAndTime(time, flag, 3);
        //服务 1零钱  2微信  3支付宝
        BigDecimal serviceLingQianMoney = ordersService.sumOrdersByCreateTime(time, flag, 1);
        BigDecimal serviceWXMoney = ordersService.sumOrdersByCreateTime(time, flag, 2);
        BigDecimal serviceZFBMoney = ordersService.sumOrdersByCreateTime(time, flag, 3);
        Map<String, Object> result = new HashMap<>();
        result.put("HelpOrderLingQianMoney", helpOrderLingQianMoney);
        result.put("HelpOrderWxMoney", helpOrderWxMoney);
        result.put("HelpOrderZFBMoney", helpOrderZFBMoney);
        result.put("serviceLingQianMoney", serviceLingQianMoney.setScale(2,BigDecimal.ROUND_DOWN));
        result.put("serviceWXMoney", serviceWXMoney.setScale(2,BigDecimal.ROUND_DOWN));
        result.put("serviceZFBMoney", serviceZFBMoney.setScale(2,BigDecimal.ROUND_DOWN));
        return Result.success().put("data", result);
    }

    @GetMapping("/getAgentProfit")
    @ApiOperation("代理收益排行榜")
    public Result getAgentProfit(Integer page, Integer limit) {
        return Result.success().put("data", ordersService.getAgentProfit(page, limit));
    }

    @GetMapping("/getStaffInfo")
    @ApiOperation("获取员工收益排行榜")
    public Result getStaffInfo(Integer page, Integer limit,Long companyId,String time,Integer flag) {
        return Result.success().put("data", ordersService.getStaffInfo(page, limit,companyId,time,flag));
    }

    @GetMapping("/getShopInfo")
    @ApiOperation("获取商户收益排行榜")
    public Result getShopInfo(Integer page, Integer limit,String time,Integer flag) {
        return Result.success().put("data", ordersService.getShopInfo(page, limit,time,flag));
    }

    @GetMapping("/getStaffOrderList")
    @ApiOperation("获取员工服务订单")
    public Result getStaffOrderList(Integer page, Integer limit, Long userId) {
        return Result.success().put("data", ordersService.getStaffOrderList(page, limit, userId));
    }

    /**
     * 关联员工
     *
     * @param userId
     * @param phone
     * @return
     */
    @PostMapping("/insertAdminStaffUser")
    public Result insertAdminStaffUser(Long userId, String phone) {
        return userService.insertAdminStaffUser(userId, phone);
    }

    /**
     * 删除员工
     *
     * @param userId
     * @param phone
     * @return
     */
    @PostMapping("/cancelStaffUser")
    public Result cancelStaffUser(Long userId, String phone) {
        return userService.cancelStaffUser(userId, phone);
    }

    /**
     * 获取商家员工服务派单量
     * @param page
     * @param limit
     * @param companyId
     * @return
     */
    @GetMapping("getStaffUserOrder")
    public Result getStaffUserOrder(Integer page,Integer limit,Long companyId){
        return Result.success().put("data", ordersService.getStaffUserOrder(page,limit,companyId));
    }

    @GetMapping("/selectStaffUserStatisticsByTime")
    @ApiOperation("员工统计")
    public Result selectStaffUserStatisticsByTime(Long userId, String time,Integer flag, Long companyId) {
        String taskTime=null;
        //派单数量
        if(StringUtils.isNotBlank(time)){
            String[] split = time.split("-");
            //获取年月日
            String month=split[1];
            month=String.valueOf(Integer.parseInt(month));
            String day=split[2];
            day=String.valueOf(Integer.parseInt(day));
            taskTime=split[0]+"-"+month+"-"+day;
        }else{
            time=null;
        }
        //派单数量
        Map<String, Object> serviceCount = ordersService.selectOrdersCountByStaffUser(userId, companyId,taskTime,  time, flag);
        //派单金额
        Map<String, Object> serviceMoney = ordersService.selectOrdersMoneyByStaffUser(userId, companyId, taskTime, time, flag);
        //派单退款数量
        Map<String, Object> refundCount = ordersService.selectOrdersRefundCountByStaffUser(userId, companyId,taskTime,  time, flag);
        //派单退款金额
        Map<String, Object> refundMoney = ordersService.selectOrdersRefundMoneyByStaffUser(userId, companyId, taskTime, time, flag);
        Map<String, Object> result = new HashMap<>();
        result.put("serviceCount", serviceCount);
        result.put("serviceMoney", serviceMoney);
        result.put("refundCount", refundCount);
        result.put("refundMoney", refundMoney);

        return Result.success().put("data", result);
    }


    @GetMapping("/selectRefundMoney")
    @ApiOperation("获取订单剩余可退金额")
    public Result selectRefundMoney(Long ordersId,Integer orderType){
        return ordersService.selectRefundMoney(ordersId, orderType);
    }

    @PostMapping("/refundMoney")
    @ApiOperation("部分退款")
    public Result refundMoney(Long ordersId,BigDecimal money,Integer orderType){
        return ordersService.refundMoney(ordersId, money, orderType);
    }

    @PostMapping("/refundOrders")
    @ApiOperation("订单退款")
    public Result refundOrders(Long ordersId,Integer orderType){
        return ordersService.refundOrders(ordersId,orderType);
    }


}
